import { ONLINE_STATUS } from '@enums/user'
import { clearJson } from '@utils'

import { pageApi } from '@/api/message'
import { 
  roomGroupUserPageApi, 
  roomGroupUserCountApi, 
  listRoomsApi, 
  getRoomDetailApi,
  inviteUsersApi,
  searchGroupsApi,
  joinGroupApi,
  getRoomAppliesApi,
  reviewRoomApplyApi
} from '@/api/room'
import { ElMessage } from 'element-plus'

export const useRoomStore = defineStore('room', {
  state: () => ({
    list: [],
    groupRooms: [], // 存储群组房间列表
  }),
  actions: {
    /**
     * 获取消息列表
     * @param {*} roomId 房间ID
     * @param {*} lastId 最后一个ID
     * @param {*} size 数据量
     * @returns
     */
    async getMessageList(roomId, lastId, size = 10) {
      const r = await pageApi({ roomId, lastId, size })
      if (r) {
        const messageList = r.data.reverse()
        const room = this.list.find(room => room.id === roomId)
        if (room) {
          const { messages } = room
          messages.unshift(...messageList)
        } else {
          this.list.push({
            id: roomId,
            messages: messageList,
            userTotalCount: 0,
            userOnlineCount: 0,
            users: []
          })
        }
        return messageList
      }
    },
    /**
     * 更新消息
     * @param {*} id 消息ID
     * @param {*} conversation 会话
     */
    updateMessage(messageId, conversation){
      const { roomId, message } = conversation
      for (let i = 0; i < this.list.length; i++) {
        const { messages } = this.list[i];
        for (let j = 0; j < messages.length; j++) {
          if (messageId === messages[j].id) {
            messages[j] = message
            return
          }
        }
      }
    },
    /**
     * 获取房间用户
     * @param {*} roomId 房间ID
     * @param {*} lastId 最后一个ID
     * @param {*} size 数据量
     * @returns 
     */
    async getUserList(roomId, lastId, size = 40) {
      const r = await roomGroupUserPageApi({ 
        room_id: roomId, 
        last_id: lastId, 
        page_size: size 
      })
      if (r && r.code === 200) {
        const userList = r.data.list || []
        const room = this.list.find(room => room.id === roomId)
        if (room) {
          const { users } = room
          users.push(...userList)
        } else {
          this.list.push({
            id: roomId,
            messages: [],
            userTotalCount: 0,
            userOnlineCount: 0,
            users: userList
          })
        }
        return userList
      }
      return []
    },
    /**
     * 获取群成员数量
     * @param {*} roomId 房间ID
     * @returns 
     */
    async getUserCount(roomId) {
      try {
        const r = await roomGroupUserCountApi({ room_id: roomId })
        if (r && r.code === 200) {
          const room = this.list.find(room => room.id === roomId)
          if (room) {
            room.userTotalCount = r.data.total
            room.userOnlineCount = r.data.online
          } else {
            this.list.push({
              id: roomId,
              messages: [],
              userTotalCount: r.data.total,
              userOnlineCount: r.data.online,
              users: []
            })
          }
          return r.data
        }
      } catch (error) {
        console.error('获取群成员数量失败:', error)
      }
    },
    
    /**
     * 新增房间 存在则新增消息 不存在则获取消息列表
     * @param {*} roomId 房间ID
     * @param {*} message 消息
     */
    addRoom(roomId, message) {
      const room = this.list.find(item => item.id === roomId)
      if (room) {
        console.log(`添加消息到房间 ${roomId}, 消息ID: ${message.id}`)
        room.messages.push(message)
      } else {
        this.getMessageList(roomId)
      }
    },
    /**
     * 添加用户
     */
    addUser(user) {
      const room = this.list.find(room => room.id === user.roomId)
      if (room) {
        const { users } = room
        const { roomUserId } = users[users.length - 1]
        if (user.roomUserId === roomUserId + 1) {
          users.push(user)
        }
        room.userTotalCount += 1
        room.userOnlineCount += 1
      }
    },
    /**
     * 更新用户信息
     * @param {*} id 房间ID
     * @param {*} nickname 消息
     */
    updateUser(user){
      this.list.forEach(room => {
        const { users } = room
        for (let i = 0; i < users.length; i++) {
          const item = users[i];
          if (item.id === user.id) {
            item.nickname = user.nickname,
            item.avatar = user.avatar,
            item.sex = user.sex
            break
          }
        }
      });
    },
    /**
     * 更新用户在线状态
     * @param {*} userId 用户ID
     * @param {*} online 在线状态
     */
    updateUserOnline(userId, online) {
      for (let i = 0; i < this.list.length; i++) {
        const room = this.list[i];
        const { users } = room
        inner:for (let j = 0; j < users.length; j++) {
          const user = users[j];
          if (user.id === userId) {
            user.online = online
            if (online === ONLINE_STATUS.ONLINE) {
              room.userOnlineCount += 1
            } else if (online === ONLINE_STATUS.OFFLINE) {
              room.userOnlineCount -= 1
            }
            break inner;
          }
        }
      }
    },
    
    /**
     * 获取群组列表
     * @returns {Promise<Array>} 群组列表
     */
    async getGroupRooms() {
      try {
        const response = await listRoomsApi()
        if (response && response.code === 200) {
          this.groupRooms = response.data || []
          return this.groupRooms
        }
        return []
      } catch (error) {
        console.error('获取群组列表失败:', error)
        return []
      }
    },
    
    /**
     * 获取群组详情
     * @param {Number} roomId 群组ID
     * @returns {Promise<Object>} 群组详情
     */
    async getGroupDetail(roomId) {
      try {
        const response = await getRoomDetailApi(roomId)
        if (response && response.code === 200) {
          // 确保群组详情包含正确的属性
          const groupData = response.data || {}
          
          // 处理群主ID：优先使用 ownerId，如果不存在则使用 creator_id
          if (groupData.ownerId === undefined) {
            groupData.ownerId = groupData.creator_id || null
          }
          
          // 更新现有群组信息
          const index = this.groupRooms.findIndex(room => room.id === roomId)
          if (index !== -1) {
            this.groupRooms[index] = {
              ...this.groupRooms[index],
              ...groupData
            }
          }
          return groupData
        }
        return null
      } catch (error) {
        console.error('获取群组详情失败:', error)
        return null
      }
    },
    
    /**
     * 更新会话中的群组详情
     * @param {Object} conversation 会话对象
     * @returns {Promise<Object>} 更新后的会话对象
     */
    async updateGroupDetails(conversation) {
      if (conversation && conversation.group && conversation.roomId) {
        try {
          const groupDetail = await this.getGroupDetail(conversation.roomId)
          if (groupDetail) {
            // 确保group对象包含完整信息
            conversation.group = {
              ...conversation.group,
              ...groupDetail,
              // 确保ownerId是有效值
              ownerId: groupDetail.ownerId || groupDetail.creator_id || null
            }
          }
        } catch (error) {
          console.error('更新群组详情失败:', error)
        }
      }
      return conversation
    },
    
    /**
     * 邀请用户加入群组
     * @param {Number} roomId 群组ID
     * @param {Array<Number>} userIds 用户ID数组
     * @returns {Promise<Boolean>} 是否成功
     */
    async inviteUsers(roomId, userIds) {
      try {
        const response = await inviteUsersApi({
          room_id: roomId,
          user_ids: userIds
        })
        if (response && response.code === 200) {
          ElMessage.success('邀请成功')
          return true
        }
        return false
      } catch (error) {
        ElMessage.error('邀请失败')
        console.error('邀请用户加入群组失败:', error)
        return false
      }
    },
    
    /**
     * 搜索群聊
     * @param {Object} params 搜索参数
     * @returns {Promise<Array>} 群聊列表
     */
    async searchGroups(params) {
      try {
        const response = await searchGroupsApi(params)
        if (response && response.code === 200) {
          return response.data || []
        }
        return []
      } catch (error) {
        console.error('搜索群聊失败:', error)
        return []
      }
    },

    /**
     * 申请加入群聊
     * @param {Number} roomId 群聊ID
     * @returns {Promise<Boolean>} 是否申请成功
     */
    async joinGroup(roomId) {
      try {
        const response = await joinGroupApi(roomId)
        if (response && response.code === 200) {
          return true
        }
        return false
      } catch (error) {
        console.error('申请加入群聊失败:', error)
        return false
      }
    },
    
    /**
     * 获取群聊申请列表
     * @param {Object} params 查询参数
     * @param {number} params.room_id 群聊ID
     * @param {number} [params.status=0] 申请状态 0-待审核 1-已通过 2-已拒绝
     * @param {number} [params.page=1] 页码
     * @param {number} [params.page_size=20] 每页数量
     * @returns {Promise<Object>} 申请列表和分页信息
     */
    async getRoomApplies(params) {
      try {
        const response = await getRoomAppliesApi(params)
        if (response && (response.code === 0 || response.code === 200)) {
          return response.data || { list: [], total: 0, page: 1, page_size: 20 }
        }
        return { list: [], total: 0, page: 1, page_size: 20 }
      } catch (error) {
        console.error('获取群聊申请列表失败:', error)
        return { list: [], total: 0, page: 1, page_size: 20 }
      }
    },

    /**
     * 审核群聊申请
     * @param {Object} data 审核数据
     * @param {number} data.id 申请ID
     * @param {number} data.status 审核状态 1-通过 2-拒绝
     * @returns {Promise<Boolean>} 是否审核成功
     */
    async reviewRoomApply(data) {
      try {
        const response = await reviewRoomApplyApi(data)
        if (response && (response.code === 0 || response.code === 200)) {
          // 如果审核通过，刷新群组列表
          if (data.status === 1) {
            await this.getGroupRooms()
          }
          return true
        }
        return false
      } catch (error) {
        console.error('审核群聊申请失败:', error)
        return false
      }
    },
    
    /**
     * 清除数据
     */
    clear() {
      clearJson(this.$state)
    },
    /**
     * 清理房间用户列表
     * @param {number} roomId 房间ID
     */
    clearRoomUsers(roomId) {
      const room = this.list.find(room => room.id === roomId)
      if (room) {
        room.users = []
        room.userTotalCount = 0
        room.userOnlineCount = 0
      }
    },
  }
})
